define(["angularAMD"], function (angularAMD) {
    angularAMD.service('QT06_SaveTemplateService', ['$state','$rootScope', '$filter', '$stateParams', 'config', '$mdDialog', 'MMWService',
        function ($state, $rootScope, $filter, $stateParams, config, $mdDialog, $MMWService) {

            var service = this;

            service.init = function(option, call_back){
                openDialog(option, call_back);
            };

            function openDialog(option, call_back){
                $mdDialog.dialog(
                    'module/moduleQT/program/QT06/dialog/QT06_SaveTemplateService.html',
                    function (dialog) {
                        return {
                            css_url: "module/moduleQT/program/QT06/dialog/QT06_SaveTemplateService.css",
                            modelName: option.modelName || '',
                            newModelName: '',
                            back: () => dialog.hide(),
                            confirm: () => {
                                dialog.hide();
                                
                                // 20220721 modify by Alan for#113392 : 修正模板名稱重複卡控
                                saveTemplate(dialog.modelName, dialog.newModelName)
                                    .then((resp) => {
                                        if(resp.Succeed === false && resp.checkNotPass === true) {
                                            $rootScope.showAlert($filter('translate')('QT06.save_template.saveDuplicate'));
                                        } else {
                                            call_back && call_back(dialog);
                                        }
                                    });
                            },
                        };
                    }
                );
            };

            const service_QTP_Step3 =  (content) => {
                return new Promise(async (resolve, reject) => {
                    let result;
                    $MMWService.sendToServer({
                        uri: "ServicesSTD.Module_LEAN.QTP_Step3",
                        content: content,
                        success: (data) => (result = resolve(data)),
                    });

                    return result;
                });
            };

            const saveTemplate = async (modelName, newModelName) => {
                const content = { Name: "SaveModelName", ModelName: modelName, NewModelName: newModelName };
                const resp = await service_QTP_Step3(content);
                return resp
            }
        }
    ])
});
